#!/bin/bash

exec_path=/home/tom/siweather/scripts
start_datetime=`date`
start=`date +%s`

exists=`ps -e | grep check_temp | wc -l`
if [ $exists -gt 2 ]; then
	echo "Already running"
	exit 1
fi

temp_start=$($exec_path/siw_control.py -d `$exec_path/get_siw_control` -t)
echo "Starting temp: "$temp_start

if [ -z "$1" ]; then
	archive=/usr/local/var/wview/archive/wview-archive.sdb
	if [ ! -f "$archive" ]; then
		echo "Archive file '"$archive"' doesn't exist"
		exit 1
	fi
	# get most recent weather station database entry
	last_entry=`sqlite3 $archive 'select * from archive order by rowid desc limit 1;'`
	bad_archive=`echo $last_entry | grep "no such table"`
	if [ $bad_archive ]; then echo "Bad database"; exit 1; fi
	# get timestamp of this entry 
	entry_time=`echo $last_entry | awk '{split($0,a,"|"); print a[1]}'`
	entry_age=`octave -q --eval "printf('%.2f',($start-$entry_time)/60)"`
	
	max_age=180 # only use dew point if less than three hours old
	too_old=`octave -q --eval "printf('%i',$entry_age>$max_age)"`
	if [ "$too_old" -eq "1" ]; then
		echo "Last entry in database is too old ("$entry_age" minutes)"
		exit 1
	fi
	dewpoint_f=`echo $last_entry | awk '{split($0,a,"|"); print a[17]}'`
	dewpoint_c=`octave -q --eval "printf('%.2f',($dewpoint_f-32)*5/9)"`
	echo "Dew point: "$dewpoint_c"     ("$entry_age" minutes ago)"
	desired=`echo $dewpoint_c" + 2" | bc`
else
	desired=$1
fi
# octave -q --eval "printf('%.2f',($f-32)*5/9)"

roof=`echo $desired" + 0.2" | bc`

echo "Desired temp: "$desired

temp=$temp_start
keep_heating=`echo "$temp < $desired" | bc`

if [ "1" -eq $keep_heating ]; then 
	$exec_path/siw_control.py -d `$exec_path/get_siw_control` -H 1
else
	message=$temp_start" on "$start_datetime
	echo $message >> /home/tom/logs/cam_temp_log
	$exec_path/siw_control.py -d `$exec_path/get_siw_control` -H 0
	exit 0
fi

while [ "1" -eq $keep_heating ]; do
	sleep 5
	temp=$($exec_path/siw_control.py -d `$exec_path/get_siw_control` -t)
	keep_heating=`echo "$temp < $roof" | bc`
	bad=`echo $keep_heating | grep illegal`
	if [ -n "$bad" ]; then keep_heating=1; fi
done

finish=`date +%s`
elapsed=$(($finish-$start))
temp_diff=`echo "$temp - $temp_start" | bc`
message=$temp_start" on "$start_datetime". Heated "$temp_diff" degrees in "$elapsed" seconds"
echo $message >> /home/tom/logs/cam_temp_log

$exec_path/siw_control.py -d `$exec_path/get_siw_control` -H 0

exit 0